import subprocess
import os
import shlex
import shutil
import queue
import logging
import re

LOGGER = logging.getLogger("Tmux")
FORMAT = '%(asctime)s %(message)s'
logging.basicConfig(format=FORMAT)
LOGGER.setLevel(logging.DEBUG)

def download_and_install_tpm(dst):
    plugin_loc = os.path.join(dst,'.tmux/plugins/tpm')
    if os.path.exists(plugin_loc):
        LOGGER.debug("{} had exist".format(plugin_loc))
    else:
        LOGGER.debug("Git clone to {}".format(dst))
        p1 = subprocess.Popen(shlex.split('git clone https://github.com/tmux-plugins/tpm {}'.format(plugin_loc)),stdout=subprocess.PIPE)
        p2 = subprocess.Popen(shlex.split('git clone https://github.com/bleedingfight/tmux-device.git {}'.format(plugin_loc)),stdout=subprocess.PIPE)

        LOGGER.debug(p1.stdout.read().decode('utf-8'))
        LOGGER.debug(p2.stdout.read().decode('utf-8'))

def config(source='.tmux.conf'):
    home = os.environ['HOME']
    out_file = os.path.join(home,source)
    shell_name = [subprocess.Popen(shlex.split('which {}'.format(name)),stdout=subprocess.PIPE).stdout.read().decode('utf-8').strip() for name in ['fish','zsh','bash']]
    shells = queue.PriorityQueue()
    [shells.put((i,s)) for (i,s) in enumerate(shell_name)]
    shell = shells.get()[1]
    with open(source,'r') as f:
        lines = f.readlines()
    with open(out_file,'w') as f:
        for no,line in enumerate(lines):
            if '/usr/bin/zsh' in line:
                line = re.sub('/usr/bin/zsh',shell,line)
                LOGGER.debug("/usr/bin/zsh was replaced as {}".format(shell))
            f.write(line)
            
    return shell
download_and_install_tpm(os.environ['HOME'])
shell = config()
    
    

